package com.taxshare.seller.service;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.taxshare.mybatis.pager.PageHelp;
import com.taxshare.mybatis.pager.PageRequest;
import com.taxshare.mybatis.utils.DozerBeanUtil;
import com.taxshare.response.beans.Response;
import com.taxshare.seller.constant.CodeConstant;
import com.taxshare.seller.entity.EquipmentEntity;
import com.taxshare.seller.mapper.EquipmentMapper;
import com.taxshare.seller.remote.ApiClientService;
import com.taxshare.seller.util.sst.IntJsonUtil;
import com.taxshare.seller.view.dto.EquipmentDTO;
import com.taxshare.seller.view.dto.SellerInvoiceDTO;
import com.taxshare.seller.view.vo.EquipmentVO;
import com.taxshare.seller.view.vo.SellerInvoiceVO;
import com.taxshare.tools.token.UserInfoUtil;
import com.taxshare.tools.util.UUIDUitl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName: EquipmentService
 * @Description:
 * @author: hjh
 * @date: 2021/6/15 14:37
 */
@Slf4j
@ConfigurationProperties(prefix = "address")
@Service
@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED)
public class EquipmentService extends ServiceImpl<EquipmentMapper, EquipmentEntity> {

    @Value("${sst.appName}")
    private String appName;

    @Value("${sst.devKey}")
    private String devKey;

    @Autowired
    ApiClientService apiClientService;

    @Autowired
    CommService commService;

    /**
     * 查询设备信息
     *
     * @param equipmentDTO
     * @return
     */
    public Response query(PageRequest<EquipmentDTO> equipmentDTO) {
        QueryWrapper<EquipmentEntity> queryWrapper = new QueryWrapper();
        EquipmentDTO equipmentInfo = equipmentDTO.getInfo();
        if (!StrUtil.hasBlank(equipmentInfo.getSellerTaxNo())) {
            queryWrapper.eq("seller_tax_no", equipmentInfo.getSellerTaxNo());
        }else {
            List<String> taxNos = commService.getTaxNumbers();
            queryWrapper.in("seller_tax_no", taxNos);
        }
        if (!StrUtil.hasBlank(equipmentInfo.getEquipmentMode())) {
            queryWrapper.eq("equipment_mode", equipmentInfo.getEquipmentMode());
        }
        if (!StrUtil.hasBlank(equipmentInfo.getPanNo())) {
            queryWrapper.eq("pan_no", equipmentInfo.getPanNo());
        }
        queryWrapper.orderByDesc("create_time");
        IPage<EquipmentVO> result = PageHelp.siamplePage(this, queryWrapper, equipmentDTO.getPage(), EquipmentVO.class);
        return Response.success(result);
    }

    /**
     * 查询设备信息
     *
     * @param equipmentDTO
     * @return
     */
    public Response query(EquipmentDTO equipmentDTO) {
        QueryWrapper<EquipmentEntity> queryWrapper = new QueryWrapper();
        String sellerTaxNo = equipmentDTO.getSellerTaxNo();
        queryWrapper.eq("seller_tax_no",sellerTaxNo);
        queryWrapper.orderByDesc("create_time");
        return Response.success(this.list(queryWrapper));
    }

    /**
     * 查询盘信息
     *
     * @return
     */
    public Response<List<EquipmentVO>> queryEquipmentList(SellerInvoiceVO sellerInvoiceVO) {
        QueryWrapper<EquipmentEntity> queryWrapper = new QueryWrapper<EquipmentEntity>();
        queryWrapper.eq("create_userid", "123");
        if (!StrUtil.hasBlank(sellerInvoiceVO.getSellerTaxNo())) {
            queryWrapper.eq("seller_tax_no", sellerInvoiceVO.getSellerTaxNo());
        }
        queryWrapper.eq("disable", "1");
        List<String> equipmenMode = new ArrayList<String>();
        equipmenMode.add("0");
        equipmenMode.add("1");
        queryWrapper.in("equipment_mode", equipmenMode);
        List<EquipmentEntity> list = this.list(queryWrapper);
        return Response.success(DozerBeanUtil.mapList(list, EquipmentVO.class));
    }

    /**
     * 新增设备信息
     *
     * @param params
     * @return
     */
    public Response add(EquipmentDTO params) {
        //税号下设备只有一个，单独查询处理
        QueryWrapper<EquipmentEntity> query = new QueryWrapper<>();
        query.eq("seller_tax_no", params.getSellerTaxNo());
        EquipmentEntity entity = this.getOne(query);
        if (entity != null) {
            return Response.error("SEL_023");
        }
        if (StrUtil.isBlank(params.getAppid()) && !params.getEquipmentMode().equals(CodeConstant.A9)) {
            return Response.error("SELLER_SBGL_007");
        }
        EquipmentEntity equipmentEntity = DozerBeanUtil.map(params, EquipmentEntity.class);
        equipmentEntity.setDisable("0");
        equipmentEntity.setUuid(UUIDUitl.UUID32(false));
        equipmentEntity.setCreateUserid(UserInfoUtil.getUserID());
        baseMapper.insert(equipmentEntity);
        return Response.success();
    }

    /**
     * 获取关联码
     *
     * @return
     * @throws UnsupportedEncodingException
     */
    public Response getRelevanceCode(String sellerTaxNo,String panNo) {
        Map map = new HashMap();
        String content = IntJsonUtil.appRegister(devKey, sellerTaxNo);
        SellerInvoiceDTO sellerRemoteVO = new SellerInvoiceDTO();
        sellerRemoteVO.setBw(content);
        Response response = apiClientService.callSST(sellerRemoteVO);
        String sstResult = (String) response.getData();
//        String sstResult = "{\"msg\":\"登记成功，请在客户端中进行关联！\",\"code\":\"00000\",\"nsrsbh\":\"\",\"data\":{\"private_secret_key\":\"4f9359451e824f61\",\"create_time\":\"2019-11-17 19:18:14\",\"crc\":\"995667\",\"appid\":\"f02984ce-1350-43d9-820d-f1e8dc37cd66\"},\"appid\":\"f02984ce-1350-43d9-820d-f1e8dc37cd66\",\"serviceid\":\"DJAPP\",\"sid\":\"\"}";
        JSONObject sstData = (JSONObject) JSON.parse(sstResult);
        log.info(sstData.toString());
        String code = sstData.getString("code");
        if (CodeConstant.THIRD_PARTY_SUCCESS.equals(code)) {
            Map dataMap = (Map) sstData.get("data");
            String list = MapUtils.getString(dataMap, "list");
            JSONArray jsonArray = JSONArray.parseArray(list);
            boolean result = false;
            for (int i = 0; i <jsonArray.size() ; i++) {
                JSONObject obj = jsonArray.getJSONObject(i);
                String appid = obj.getString("appid");
                String sbbh = obj.getString("sbbh");
                if (sbbh.equals(panNo)) {
                    map.put("appid", appid);
                    result = true;
                }
            }
            if (result == true) {
                return Response.success(map);
            } else {
                return Response.error("SEL_044");
            }
        } else {
            return Response.error("SEL_022");
        }
    }

    /**
     * 更新设备
     *
     * @param params
     * @return
     */
    public Response update(EquipmentDTO params) {
        EquipmentEntity entity = DozerBeanUtil.map(params, EquipmentEntity.class);
        if (!updateById(entity)) {
            return Response.error();
        }
        return Response.success();
    }

    /**
     * 删除设备
     *
     * @param uuid
     * @return
     */
    public Response delete(String uuid) {
        int i = baseMapper.deleteById(uuid);
        if (i > 0) {
            return Response.success();
        } else {
            return Response.error("SEL_021");
        }
    }

    /**
     * 启用/禁用
     *
     * @param params
     * @return
     */
    public Response disable(EquipmentDTO params) {
        String disable = params.getDisable();
        EquipmentEntity equipmentEntity = this.getById(params.getUuid());
        equipmentEntity.setDisable(disable);
        equipmentEntity.setUpdateUserid(UserInfoUtil.getUserID());
        this.updateById(equipmentEntity);
        return Response.success();
    }

    /**
     * 获取设备状态和类型
     * @param sellerTaxNo
     * @return
     */
    public EquipmentEntity queryEquipment(String sellerTaxNo){
        QueryWrapper<EquipmentEntity> queryEquipment = new QueryWrapper<>();
        queryEquipment.eq("seller_tax_no",sellerTaxNo);
        EquipmentEntity equipmentEntity = baseMapper.selectOne(queryEquipment);
        return equipmentEntity;
    }
}


